package in.co.codedoc.encode;

import in.co.codedoc.util.HexUtil;

public class URIEncoding
{
	public static String Encode(String text)
	{
		StringBuffer buffer = new StringBuffer();
		
		char[] chars = text.toCharArray();
		
		for (int i = 0; i < chars.length; i++)
		{
			switch(chars[i])
			{
				case '!':
				case '*':
				case '\'':
				case '"':
				case '(':
				case ')':
				case ';':
				case ':':
				case '@':
				case '&':
				case '=':
				case '+':
				case '$':
				case ',':
				case '/':
				case '?':
				case '%':
				case '#':
				case '[':
				case ']':
				case ' ':
					buffer.append('%');
					HexUtil.PrintHexDigits(buffer,((byte)chars[i]));
					break;
				default:
					buffer.append(chars[i]);
					break;
			}
		}
		
		return buffer.toString();
	}
	
	public static String Decode(String text)
	{
		StringBuffer buffer = new StringBuffer();
		
		char[] chars = text.toCharArray();
		
		for (int i = 0; i < chars.length; i++)
		{
			if(chars[i] == '%')
			{
				try
				{
					buffer.append(HexUtil.DecodeHexDigits(chars, i+1));
					i += 2;
				}
				catch(IllegalArgumentException ex)
				{
					buffer.append(chars[i]);
				}
			}
			else
			{
				buffer.append(chars[i]);
			}
		}
		
		return buffer.toString();
	}
}
